#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

void Usage(const std::string &proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

// ./tcpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    //从命令行参数获取服务器的端口和ip
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    // 初始化地址信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    // 将ip转换成网络字节序
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr)); 

    int sockfd = 0;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);//创建套接字

    // 客户端发起connect的时候，进行自动随机bind
    //链接服务器
    int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
    if (n < 0)
    {
        std::cout << "链接失败, reconnect: " << std::endl;
        sleep(2);
    }

    while (true)
    {
        std::string message;
        std::cout << "Please Enter# ";
        std::getline(std::cin, message);

        int n = write(sockfd, message.c_str(), message.size());//发送数据
        if (n < 0)
        {
            std::cout << "write出错" << std::endl;
            // break;
        }

        char inbuffer[4096];
        n = read(sockfd, inbuffer, sizeof(inbuffer));//接收反馈
        if (n > 0)
        {
            inbuffer[n] = 0;
            std::cout << inbuffer << std::endl;
        }
    }
    close(sockfd);

    return 0;
}